package com.gmall.security.vo;

import com.gmall.user.api.po.User;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;

@Data
public class JwtUser implements UserDetails {

    private String id;

    private String username;

    private String password;

    /**
     * 所属公司id
     */
    private String companyId;

    private Collection<? extends GrantedAuthority> authorities;

    // 写一个能直接使用user创建jwtUser的构造器
    public JwtUser(User user) {
        id = (String) user.getId();
        username = user.getUsername();
        password = user.getPassword();
        companyId = user.getCompanyId();

        // 添加至权限管理
        List<GrantedAuthority> list = new ArrayList<>();
        Optional.ofNullable(user.getRoles()).ifPresent(roles -> roles.stream().forEach(e -> list.add(new SimpleGrantedAuthority(e))));
        authorities = list;
    }

    // 账号是否未过期，默认是false，改为默认 true
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    // 账号是否未锁定，默认是false，改为默认 true
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    // 账号凭证是否未过期，默认是false，改为默认 true
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    // 这个有点抽象不会翻译，默认也是false，改为默认 true
    @Override
    public boolean isEnabled() {
        return true;
    }
}

